package com.hyy.customer.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyy.api.constant.CommonConstant;
import com.hyy.api.domain.system.SysRole;
import com.hyy.api.domain.system.SysUser;
import com.hyy.api.domain.system.SysUserRole;
import com.hyy.api.domain.system.bo.SysUserBo;
import com.hyy.common.core.utils.MapstructUtils;
import com.hyy.customer.mapper.ModCstmSysRoleMapper;
import com.hyy.customer.mapper.ModCstmSysUserMapper;
import com.hyy.customer.mapper.ModCstmSysUserRoleMapper;
import com.hyy.customer.service.IModCstmSysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ModCstmSysUserServiceImpl implements IModCstmSysUserService {

    private final ModCstmSysUserMapper baseMapper;
    private final ModCstmSysUserRoleMapper userRoleMapper;
    private final ModCstmSysRoleMapper roleMapper;


    @Override
    public int insertCorporateUser(SysUserBo user) {

        SysUser sysUser = MapstructUtils.convert(user, SysUser.class);
        // 密码加密
        sysUser.setPassword(BCrypt.hashpw(user.getPassword()));
        // 新增用户信息
        int rows = baseMapper.insert(sysUser);
        user.setUserId(sysUser.getUserId());
        // 获取corporate权限的数据
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getRoleKey, CommonConstant.CORPORATE_ROLE_NAME);
        SysRole sysRole = roleMapper.selectOne(wrapper);

        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(sysUser.getUserId());
        userRole.setRoleId(sysRole.getRoleId());
        userRoleMapper.insert(userRole);

        return rows;
    }

    @Override
    public int insertCustomerUser(SysUserBo user) {
        SysUser sysUser = MapstructUtils.convert(user, SysUser.class);
        // 密码加密
        sysUser.setPassword(BCrypt.hashpw(user.getPassword()));
        // 新增用户信息
        int rows = baseMapper.insert(sysUser);
        user.setUserId(sysUser.getUserId());
        // 获取corporate权限的数据
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getRoleKey, CommonConstant.CUSTOMER_ROLE_NAME);
        SysRole sysRole = roleMapper.selectOne(wrapper);

        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(sysUser.getUserId());
        userRole.setRoleId(sysRole.getRoleId());
        userRoleMapper.insert(userRole);

        return rows;
    }

    @Override
    public void deleteByCode(String code) {

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName, code);
        baseMapper.delete(wrapper);
    }


    public static void main(String[] args) {
        String hashpw = BCrypt.hashpw("123456");

        System.out.println(hashpw);
    }
}
